<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsers">
            <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="Users" stripe border style="margin-top: 15px">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="toggleSwitch(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="editUser(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteUser(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" @click="allocatingUser(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="35%" @close="addDialogClear">
        <el-form :model="addUserForm" status-icon :rules="rules" ref="addUserForm" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="35%" @close="editDialogClear">
        <el-form :rules="rules" :model="editUserForm" ref="editUserForm" label-width="70px">
          <el-form-item label="用户名">
            <el-input v-model="editUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="updateUserInfo">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="分配角色" :visible.sync="allocatingDialogVisible" width="35%">
        <div>
          <p>当前用户：{{userInfo.username}}</p>
          <p>当前角色：{{userInfo.role_name}}</p>
          <p>分配新角色：
            <el-select v-model="value" placeholder="请选择">
              <el-option v-for="item in options" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="allocatingDialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="allocatingRolse">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    const checkEmail = (rule, value, cb) => {
      const regEmail = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    const checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      Users: [],
      addDialogVisible: false,
      editDialogVisible: false,
      allocatingDialogVisible: false,
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3-10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '密码的长度在3-10个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editUserForm: {},
      userInfo: {},
      options: [],
      value: ''
    }
  },
  methods: {
    async getUsers () {
      const { data } = await this.$http.get('/users', { params: this.queryInfo })
      if (data.meta.status === 200) {
        this.Users = data.data.users
        this.total = data.data.total
      }
    },
    async editUser (id) {
      this.editDialogVisible = !this.editDialogVisible
      const { data } = await this.$http.get(`users/${id}`)
      if (data.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.editUserForm = data.data
    },
    async toggleSwitch (userInfo) {
      const { data } = await this.$http.put(`/users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (data.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        this.$message.error('更新用户状态失败')
      } else {
        this.$message.success('更新用户状态成功')
      }
    },
    addUser () {
      this.$refs.addUserForm.validate(async valid => {
        if (valid) {
          const { data } = await this.$http.post('users', this.addUserForm)
          // console.log(data)
          if (data.meta.status !== 201) return this.$message.error('添加用户失败')
          this.$message.success('添加用户成功')
          this.addDialogVisible = false
          this.getUsers()
        }
      })
    },
    updateUserInfo () {
      this.$refs.editUserForm.validate(async valid => {
        if (valid) {
          const { data } = await this.$http.put(`users/${this.editUserForm.id}`, this.editUserForm)
          if (data.meta.status !== 200) return this.$message.error('更新用户信息失败')
          this.$message.success('更新用户成功')
          this.editDialogVisible = false
          this.getUsers()
        }
      })
    },
    deleteUser (id) {
      this.$confirm('是否永久删除该用户', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data } = await this.$http.delete(`users/${id}`)
        if (data.meta.status !== 200) return this.$message.error(`${data.meta.msg}`)
        this.$message.success('删除成功!')
        this.getUsers()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async allocatingUser (rowObj) {
      this.allocatingDialogVisible = !this.allocatingDialogVisible
      this.userInfo.id = rowObj.id
      this.userInfo.username = rowObj.username
      this.userInfo.role_name = rowObj.role_name
      const { data } = await this.$http.get('roles')
      if (data.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.options = data.data
    },
    async allocatingRolse () {
      if (!this.value) return this.$message.error('请选择要分配的角色')
      const { data } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.value })
      if (data.meta.status !== 200) return this.$message.error(`${data.meta.msg}`)
      this.$message.success(`${data.meta.msg}`)
      this.allocatingDialogVisible = !this.allocatingDialogVisible
    },

    addDialogClear () {
      this.$refs.addUserForm.resetFields()
    },
    editDialogClear () {
      this.$refs.editUserForm.resetFields()
    },

    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUsers()
    },
    handleCurrentChange (newCurrent) {
      this.queryInfo.pagenum = newCurrent
      this.getUsers()
    }
  },
  created () {
    this.getUsers()
  }
}
</script>

<style lang="scss" scoped>
</style>
